﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ScannerApp.Common;
using ScannerApp.Models;
using System.Data;
using System.Threading;
using System.IO;
using AutoUpdate.Log;
using System.Net;

namespace ScannerApp.Business
{
    /// <summary>
    /// VIT.xaml 的交互逻辑
    /// </summary>
    public partial class VIT : Window
    {
        ScanApp.ScanAppSoapClient sa = new ScanApp.ScanAppSoapClient();

        ViewModel vm;
        Dictionary<string, string> SendList = new Dictionary<string, string>();
        Dictionary<string, string> ReciveList = new Dictionary<string, string>();
        ScanApp.Boar_ISASpSUS bi = new ScanApp.Boar_ISASpSUS();
        private TcpClient tcpcz = null;
        private bool _isLoadSuccess = false;


        public VIT()
        {
            InitializeComponent();
             czy.Text = publicclass.UserName;
            vm = (ViewModel)this.DataContext;
            vm.FocusLastItem += AutoScroll;
            vm.AddItemsToStatus("初始化...",0);
        }

        private void close_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {

            MessageBoxResult result = System.Windows.MessageBox.Show("系统是否关闭？", "提示", MessageBoxButton.YesNo);
            if (result == MessageBoxResult.Yes)
            {
                System.Windows.Application.Current.Shutdown();    Environment.Exit(0);
            }
            else
            {

            }

        }

        private void tm1_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                this._loading.Visibility = Visibility.Visible;

                //button1.Focus();
                LoadData(tm1.Text);
                tm1.Text = "";
                this._loading.Visibility = Visibility.Collapsed;
            }



        }

        private void read_Click(object sender, MouseButtonEventArgs e)
        {

            if (!IsConnected)
            {
                if (!_isLoadSuccess)
                {
                    string ISASpSUSpath = Common.ConfigHelper.GetIni("ISASpSUSpath", "");
                    _isLoadSuccess = ctnTest.StartAndEmbedProcess(ISASpSUSpath);
                }
                InitTcpIP();
            }
            else
            {
                if (!IsGet)
                {
                    Tips("先获取数据,然后再提交！"); return;
                }
                vm.listStatusClear();
                this._loading.Visibility = Visibility.Visible;

                string msg = sa.Update_boar_collection_status("VIT", zydh.Text.Trim());
                string addmsg = sa.Add_boar_ISASpSUS(bi);
                if (zydh.Text.Trim() != "" && msg == "" && addmsg == "")
                {

                    string para = "{\"EventType\":\"种禽活力分析\",\"EventID\":\"" + publicclass.MacAddress + "\",\"EventTitle\":\"" + zydh.Text + "\",\"Log_Content\":\"" + "【采集保存(状态)】 → 15\",\"UserID\":\"" + publicclass.Id + "\",\"UserName\":\"" + publicclass.UserName + "\"}";
                    string msglog = sa.Sys_log(para);
                    Clear();
                    //保存
                    SendClient(ISASpSUSSendCommond.savedata + "\r\n");


                }
                else
                {
                    Tips(msg + addmsg);
                }

                this._loading.Visibility = Visibility.Collapsed;
            }
            IsGet = false;

        }
        bool IsGet = false;
        //RoutedEventArgs e
        private void save_Click(object sender, MouseButtonEventArgs e)
        {

            if (zydh.Text.Trim() == "")
            {
                Tips("无有效数据，无法获取！");
                return;
            }
            this._loading.Visibility = Visibility.Visible;
            ReciveData(1);
            IsGet = true;
            Tips("请确保ISAS软件已经捕获并分析！！");
            this._loading.Visibility = Visibility.Collapsed;
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            _loading.Visibility = Visibility.Visible;
            //Join WinAPI Setting Focse();  
            //IntPtr handle = new WindowInteropHelper(this).Handle;
            //double y1 = SystemParameters.FullPrimaryScreenHeight;

            //double x1 = SystemParameters.FullPrimaryScreenWidth;//得到屏幕整体高度
            //SetWindowPos(handle, HWND_TOPMOST, 0, 0, (int)350 , (int)1000, SWP_SHOWWINDOW);
            this.WindowState = System.Windows.WindowState.Maximized;

            tm1.Focus();
            sysname.Text = publicclass.SystemName;
            string preurl = Common.ConfigHelper.GetEndpointClientAddress("ScanAppSoap");

            Uri uri = new Uri(preurl);
            string imageurl = uri.Scheme + "://" + uri.Host + "/" + publicclass.SystemLogo;
            // Console.WriteLine(uri.Host);
            this.tb_1.Source = new BitmapImage(new Uri(imageurl));
            //初始化条码
            //tm();
            ////初始化发送/接收
            //InitIASApSUSData();
            //
            InitTcpIP();
            if (!_isLoadSuccess)
            {
                string ISASpSUSpath = Common.ConfigHelper.GetIni("ISASpSUSpath","");
                _isLoadSuccess = ctnTest.StartAndEmbedProcess(ISASpSUSpath);
            }
            _loading.Visibility = Visibility.Collapsed;

        }
        private void Window_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                DragMove();
            }
        }

        void LoadData(string tm)
        {
            if (tm.Length <= 1)
            {
                Tips(tm + "条码无效");
            }


            DataTable lsdt = sa.GetDataTable_collection_condition(tm, "VIT");
            if (lsdt == null)
            {
                Clear();
                Tips(tm + "无对应订单信息");
            }
            else
            {
                if (lsdt.Rows.Count <= 0)
                {
                    Clear();
                    Tips(tm + "无对应订单信息");
                }
                else
                {
                    //新增
                    string msgs = ISASpSUSSendCommond.newanalysis;
                    string sendmsg = msgs + "\r\n";
                    SendClient(sendmsg);

                    foreach (DataRow dr in lsdt.Rows)
                    {
                        zydh.Text = dr["id"].ToString();
                        ddbh.Text = dr["Serialnumber"].ToString();
                        cpsl.Text = dr["quantity"].ToString();
                        mfrl.Text = dr["capacity"].ToString();
                        ddjq.Text = dr["Order_date"].ToString();
                        //yysj.Text = dr["collectDate"].ToString();
                        ddzt.Text = dr["StatusName"].ToString();

                        bi.collectionID = dr["id"].ToString();
                        //一次剂量
                        int dosisvolume = int.Parse(dr["quantity"].ToString());
                        bi.dosisvolume = dosisvolume;
                        SendClient(ISASpSUSSendCommond.putdata_dosisvolume + " " + dosisvolume.ToString() + "\r\n");
                        //collector
                        bi.collector = dr["uid"].ToString();
                        SendClient(ISASpSUSSendCommond.putdata_collector + " " + dr["uid"].ToString() + "\r\n");
                        //operator
                        bi.c_operator = publicclass.UserID;
                        SendClient(ISASpSUSSendCommond.putdata_operator + " " + publicclass.UserID + "\r\n");
                        //称重量
                        int ej = int.Parse(dr["weights"].ToString());
                        bi.ejaculatedvolume = ej;
                        SendClient(ISASpSUSSendCommond.putdata_ejaculatedvolume + " " + ej.ToString() + "\r\n");
                        //种禽名称
                        bi.c_subject = dr["barcode"].ToString();
                        SendClient(ISASpSUSSendCommond.putdata_subject + " " + dr["barcode"].ToString() + "\r\n");

                    }

                }

            }

        }

        void Clear()
        {
            vm.listStatusClear();

            zydh.Text = "";
            ddbh.Text = "";
            cpsl.Text = "";
            mfrl.Text = "";
            ddjq.Text = "";
            //yysj.Text = "";
            ddzt.Text = "";

        }

        void tm()
        {
            System.Drawing.Image image = BarcodeHelper.GenerateCZ("00000000", 200, 50);

            // DisplayImg(image, cztm); 

        }

        void DisplayImg(System.Drawing.Image image, System.Windows.Controls.Image cimage)
        {
            //System.Drawing.Image image = BarcodeHelper.GenerateCZ("00000000", 200, 50);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);// 格式自处理,这里用 bitmap
                                                                   // 下行,初始一个 ImageSource 作为 myImage 的Source
            System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage();
            bi.BeginInit();
            bi.StreamSource = new MemoryStream(ms.ToArray()); // 不要直接使用 ms
            bi.EndInit();
            cimage.Source = bi; // done!
            ms.Close();
        }
        //从服务器获取全部有效数据
        int recvice = 0;

        void ReciveData(int rsend)
        {
            //SendClient(ISASpSUSSendCommond.savedata + "\r\n");

            recvice = rsend;
            switch (rsend)
            {
                case 1:
                    SendClient(ISASpSUSReciveCommond.getdata_casereference + "\r\n");
                    break;
                case 2:
                    SendClient(ISASpSUSReciveCommond.getdata_produceddosis + "\r\n");
                    break;
                case 3:
                    SendClient(ISASpSUSReciveCommond.getdata_diluentvolume + "\r\n");
                    break;
                case 4:
                    SendClient(ISASpSUSReciveCommond.getdata_totalfinalvolume + "\r\n");
                    break;



            }
        }

        void InitIASApSUSData()
        {
            //SendList.Add(XHDre, "");
            SendList.Add("putdata_collector", "");
            SendList.Add("putdata_operator", publicclass.UserID);
            SendList.Add("putdata_dosisvolume", "");
            SendList.Add("putdata_subject", "");
            SendList.Add("putdata_ejaculatedvolume", "");

            ReciveList.Add("getdata_casereference", "");
            ReciveList.Add("getdata_produceddosis", "");
            ReciveList.Add("getdata_diluentvolume", "");
            ReciveList.Add("getdata_totalfinalvolume", "");
        }

        void Tips(string msg)
        {
            vm.AddItemsToStatus("错误:" + msg, 2);

            // PopMessageHelper.ShowMessage("错误:" + msg + "！\r\n窗口3秒后关闭...", "提示", 3000, MsgStyle.RedCritical_OK);
            Logger.Instance.WriteLog(publicclass.UserName + "[种源采集]" + msg, LogType.Error, "Density");
            tm1.Focus(); return;
        }
        void UIAction(Action action)//在主线程外激活线程方法
        {
            System.Threading.SynchronizationContext.SetSynchronizationContext(new System.Windows.Threading.DispatcherSynchronizationContext(App.Current.Dispatcher));
            System.Threading.SynchronizationContext.Current.Post(_ => action(), null);
        }
        /// <summary>
        /// 滚动条自动滚动
        /// </summary>
        private void AutoScroll()
        {
            StatusList.ScrollIntoView(StatusList.Items[StatusList.Items.Count - 1]);
        }

        private void InitTcpIP()
        {
            if (!IsConnected)
            {
                string ip = "127.0.0.1";//"127.0.0.1";"192.168.1.109"
                int port = 3000;
                Connect(ip, port);
            }

            //tcpip_client.RemoteIp = "127.0.0.1";
            //tcpip_client.RemotePort = 3000;
            //if (!tcpip_client.IsConnected)
            //{
            //    tcpip_client.ConnectToServer();
            //}

            if (!IsConnected)
            {
                read.Text = "连接TCP";
                UIAction(() =>
                {
                    red.Text = "连接失败！请先打开ISASpSUS！";
                });
                vm.AddItemsToStatus("连接失败！请先打开ISASpSUS！", 2);
            }
            else
            {
                read.Text = "提交";
                UIAction(() =>
                {
                    green.Text = "连接成功！";
                });
                vm.AddItemsToStatus("连接成功！", 0);
            }


        }


        public void ShowData(string msg)
        {
            vm.AddItemsToStatus("接收:" + msg, 0);
        }


        #region TCPIP
        public bool IsConnected = false;
        Socket socketClient = null;
        Thread threadClient = null;
        public void Connect(string ipaddress, int portNum)
        {
            IPAddress address = IPAddress.Parse(ipaddress);
            IPEndPoint endPoint = new IPEndPoint(address, portNum);
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                vm.AddItemsToStatus("与服务器连接中", 0);
                socketClient.Connect(endPoint);

            }
            catch (SocketException se)
            {
                vm.AddItemsToStatus("连接失败！" + se.Message, 2);
                IsConnected = false;
                return;
            }
            vm.AddItemsToStatus("连接成功！", 0);
            IsConnected = true;
            threadClient = new Thread(RecMsg);
            threadClient.IsBackground = true;
            threadClient.Start(socketClient);
        }

        //处理tcp接收的数据。
        void RecMsg(object sockConnectionparn)
        {
            Socket sockConnection = sockConnectionparn as Socket;
            EndPoint remoteEndPoint = new IPEndPoint(0, 0); ;
            byte[] buffMsgRec = new byte[1024];//* 1024 * 10

            int length = -1;

            while (true)
            {

                try
                {


                    length = sockConnection.Receive(buffMsgRec);
                    string receiveText = System.Text.Encoding.Default.GetString(buffMsgRec, 0, length);// 将接受到的字节数据转化成字符串；  
                    UIAction(() =>
                    {
                        vm.AddItemsToStatus(receiveText, 1);
                        if (receiveText == "ok\r\n")
                        {

                        }
                        else
                        {
                            //int rrecive = 1;
                            receiveText = receiveText.Replace("\r\n", "");
                            switch (recvice)
                            {
                                case 1:
                                    bi.casereference = receiveText;
                                    ReciveData(2);
                                    break;
                                case 2:
                                    bi.produceddosis = int.Parse(receiveText);
                                    ReciveData(3);
                                    break;
                                case 3:
                                    bi.diluentvolume = int.Parse(receiveText);
                                    ReciveData(4);
                                    break;
                                case 4:
                                    bi.totalfinalvolume = int.Parse(receiveText);
                                    recvice = 0;
                                    break;
                            }

                        }
                    });


                }

                catch (SocketException se)
                {
                    vm.AddItemsToStatus(se.Message, 2);
                    return;

                }
                catch (ThreadAbortException te)
                {
                    vm.AddItemsToStatus(te.Message, 2);
                    return;

                }
                catch (Exception e)
                {
                    vm.AddItemsToStatus(e.Message, 2);
                    return;

                }



                Thread.Sleep(10);


            }


        }
        //断开连接
        public void UnConnect()
        {
            try
            {
                threadClient.Abort();
                socketClient.Close();
            }
            catch (Exception e)
            {
                vm.AddItemsToStatus(e.Message, 2);
                return;
            }
            vm.AddItemsToStatus("已经断开连接！", 2);
            IsConnected = false;
        }



        //发送数据
        public void SendClient(string Msg)
        {
            SendMsg(socketClient, Msg);
            Thread.Sleep(100);
        }
        //发送数据
        private void SendMsg(object sockConnectionparn, string SendMsg)
        {
            Socket sockConnection = sockConnectionparn as Socket;

            if (!sockConnection.IsBound)
            {
                vm.AddItemsToStatus("请先建立连接！", 2);
                return;
            }
            try
            {
                string sendData = SendMsg;    //复制发送数据

                //字符串发送

                //serial.Write(sendData);
                byte[] arrData = System.Text.Encoding.Default.GetBytes(sendData);
                int i = sockConnection.Send(arrData);

                if (i > 0)
                    return;
                else
                {
                    vm.AddItemsToStatus("发送0个字节！", 2);
                    return;
                };

            }
            catch (Exception ex)
            {
                vm.AddItemsToStatus(ex.Message, 2);
                return;
            }

        }
        #endregion

    }
}
